package com.dji.compose_learning

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.dji.compose_learning.ui.view.CodeView

class CodeShowActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Surface(modifier = Modifier
                .fillMaxSize(),
                color = MaterialTheme.colorScheme.background) {
                CodeView("""
/*
考虑几点内容：
1.可以求平方根的数都是正数（实数范围内）
2.当x小于1时，其平方根都大于x
3.当x大于1时，其平方根都小于x
4.特殊情况，1的平方根为1，0的平方根为0
 */
class Scratch {
    public static void main(String[] args) {
        System.out.println(sqrt(8));
        System.out.println(sqrt(0.8));
    }

    public static Double sqrt(double target) {
        if (target < 0) {
            return null;
        }
        if (target == 0 || target == 1) {
            return target;
        }

        if (target>1) {
            return coreSqrt(target, 1, target, 0.00000001);
        } else {
            return coreSqrt(target, target, 1, 0.00000001);
        }
    }

    public static Double coreSqrt(double target, double rangeMin, double rangeMax, double precision) {
        double currentResult = (rangeMin + rangeMax) / 2;
        if (Math.abs(currentResult * currentResult - target) <= precision) {
            return currentResult;
        }
        System.out.println(currentResult);
        if (target < currentResult * currentResult) {
            return coreSqrt(target, rangeMin, currentResult, precision);
        } else {
            return coreSqrt(target, currentResult, rangeMax, precision);
        }
    }
}




   /**
     * 牛顿迭代
     * x = n*n
     * x/n = n
     * x/n * n = x
     * 已知（x/n + n）/2 的平方比x/n的平方更接近于x 所以可以依据此规律进行递归
     */
    public static double sqrt2(double target) {
        if (target < 0) {
            return -1;
        }
        if (target == 0 || target == 1) {
            return target;
        }

        return coreSqrt1(target, target, 0.00000000001);
    }

    public static double coreSqrt1(double target, double result,double precision) {
//        System.out.println(result);
        if (Math.abs(result * result - target)<precision) {
            return result;
        } else {
            return coreSqrt1(target, (target / result + result) / 2,precision);
        }
    }
""")
            }
        }
    }
}






















